const Controller = require('egg').Controller;
const { HttpExceptions } = require('../exceptions/http_exceptions.js');

class BaseController extends Controller {
	
  //获取参数
  async getParams(ctx,validate=false){
		let params = {}
	  if(ctx.request.method == 'GET'){
		  params = ctx.request.query
	  }else if(ctx.request.method == 'POST'){
			params = ctx.request.body
	  }
	  if(validate){
		  let validateResult = await ctx.validate(validate,params)
		  if (!validateResult) {
			  this.ApiException(ctx.body.msg,ctx.body.errorCode,401,ctx.body.errors)
		  }else{
			  return await params
		  }
	  }else{
		  return await params
	  }
  }
	
  //成功返回
  showSuccess(data = [],msg = 'ok',code = 200) {
  	this.ctx.body = {
  		msg,
  		data
  	}
  	this.ctx.status = code
  }
  
  //错误异常
  ApiException(msg = '请求错误',errorCode = 20000,statusCode = 401,errors = false){
	  throw new HttpExceptions(msg,errorCode,statusCode,errors)
  }
	
}

module.exports = BaseController;